package com.home.andromo;

import java.util.ArrayList;




import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.os.Bundle;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;



public class andromoActivity extends ListActivity {

  
        private GridView mListAppInfo;
        private int requestCode;
        private AndromoDbHelper dBHelp; // para tener acceso desde el onResume
		private int categoryPostion=1;
		private ArrayList<MenuCat> categorias = new ArrayList<MenuCat>();

        @Override
        public void onCreate(Bundle savedInstanceState) {
        	
        	dBHelp = new AndromoDbHelper(getApplicationContext());
        	
        	
    		
        	/*
        	dBHelp.guardarApps("com.imdb.mobile", "", 1);
        	dBHelp.guardarApps("com.netflix.mediaclient", "", 1);
        	dBHelp.guardarApps("com.plexapp.android", "", 1);
        	dBHelp.guardarApps("com.skype.raider", "", 1);
        	dBHelp.guardarApps("com.facebook.katana", "", 1);
        	
        	dBHelp.guardarApps("com.android.calculator2", "", 1);
        	dBHelp.guardarApps("com.android.browser", "", 1);
        	dBHelp.guardarApps("com.android.calendar", "", 1);
        	dBHelp.guardarApps("com.android.contacts", "", 1);
        	*/
  
        	dBHelp.guardarApps("com.imdb.mobile", "", 2);
        	dBHelp.guardarApps("com.netflix.mediaclient", "", 2);
        	
        	
        	        	
            super.onCreate(savedInstanceState);
            // set layout for the main screen
            setContentView(R.layout.tv);
            
           	
        	ListView listView = (ListView) findViewById(android.R.id.list);

        	
        	categorias.add(new MenuCat(1,"Home",null));
        	categorias.add(new MenuCat(2,"News",null));
        	categorias.add(new MenuCat(3,"Movies",null));
        	categorias.add(new MenuCat(4,"Config","com.android.settings"));
        	
        	
        	
        	listView.setOnItemClickListener(new OnItemClickListener() {
        		@Override
        		public void onItemClick(AdapterView<?> parent, View view,
        			int position, long id) {
        			/*Toast.makeText(getApplicationContext(),
        				"Click ListItem Number " + position, Toast.LENGTH_LONG)
        				.show();*/
        			categoryPostion=position+1;
        			if(categorias.get(position).getPaquete()!= null){
        				categoryPostion=1;
                		Utilities.launchApp(parent.getContext(), getPackageManager(), categorias.get(position).getPaquete());
        			}else{
        			cargarAppsCategoria(position+1);
        			}
        		}
        	}); 

        	// First paramenter - Context
        	// Second parameter - Layout for the row
        	// Third parameter - ID of the View to which the data is written
        	// Forth - the Array of data
        	
        	
        	listView.setAdapter(new CategoryItemAdapter(this, R.layout.category_item, categorias));
        	
        	cargarAppsCategoria(1);

        }
        
        
        
        
        
        private void cargarAppsCategoria(int i) {
			// TODO Auto-generated method stub
        	
        	 /*ESTA PARTE LA COPIA AL ON-RESUME*/
            // load list application
            mListAppInfo = (GridView)findViewById(R.id.lvApps);
            // create new adapter
            AppInfoAdapter adapter = new AppInfoAdapter(this, Utilities.getInstalledApplication(this,dBHelp.SelectDatosPorIdCategoria(i)), getPackageManager());
            // set adapter to list view
            mListAppInfo.setAdapter(adapter);
            
            
            // implement event when an item on list view is selected
             mListAppInfo.setOnItemClickListener(new OnItemClickListener() {
            	@Override
            	public void onItemClick(AdapterView parent, View view, int pos, long id) {
            		// get the list adapter
            		AppInfoAdapter appInfoAdapter = (AppInfoAdapter)parent.getAdapter();
            		// get selected item on the list
            		ApplicationInfo appInfo = (ApplicationInfo)((Application)appInfoAdapter.getItem(pos)).getApp();
            		// launch the selected application
            		Utilities.launchApp(parent.getContext(), getPackageManager(), appInfo.packageName);
            	}
    		});
             
			
		}





		@Override        
        public void onResume(){
        	super.onResume();
        	 // load list application
            mListAppInfo = (GridView)findViewById(R.id.lvApps);
            // create new adapter
            AppInfoAdapter adapter = new AppInfoAdapter(this, Utilities.getInstalledApplication(this,dBHelp.SelectDatosPorIdCategoria(categoryPostion)), getPackageManager());
            // set adapter to list view
            mListAppInfo.setAdapter(adapter);        	
        }
    

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_andromo, menu);
        return true;
    }
    
 // METODO DE CONTROL DEL BOTON MENU
 	@Override
 	public boolean onOptionsItemSelected(MenuItem item) {
 		switch (item.getItemId()) {
 		case R.id.menu_seleccion: 			
 			Intent intento = new Intent(this, ActividadSeleccionCategoria.class);
 			
 			intento.putExtra("category_name", categoryPostion);
 	    	startActivityForResult(intento, requestCode ); // AQUI HAY POR APRENDER!
 	    	break;
 		case R.id.menu_eliminacion: 			
 			Intent intento2 = new Intent(this, ActividadSacarCategoria.class);
 			
 			intento2.putExtra("category_name", categoryPostion);
 	    	startActivityForResult(intento2, requestCode ); // AQUI HAY POR APRENDER!
 	    	break;
 		} 		
 		return true; 		
 	}
 	
 // ESTE METODO RECIBE EL PAQUETE AGREGADO
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("CheckStartActivity","onActivityResult and resultCode = "+resultCode);
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==1){                        
            String pqRecibido ="no llego nada!";
    	    pqRecibido = data.getStringExtra("added_package");
            Log.d("ESPERANDO.... ","RETORNO EL PAQUETE = "+ pqRecibido);
    	   /* Toast.makeText(this, pqRecibido, Toast.LENGTH_LONG).show();*/  
    	            }
        else{
            /*Toast.makeText(this, "Fail", Toast.LENGTH_LONG).show();*/
        }
    }

 
    public class CategoryItemAdapter extends ArrayAdapter<MenuCat> {
		private ArrayList<MenuCat> categorias;

		public CategoryItemAdapter(Context context, int textViewResourceId,
				ArrayList<MenuCat> categorias) {
			super(context, textViewResourceId, categorias);
			this.categorias = categorias;
		}
		
		

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.category_item, null);
			}

			String categoria = categorias.get(position).getNombre();
			if (categorias != null) {
				TextView cat = (TextView) v.findViewById(R.id.categoria);
				
				if (cat != null) {
					cat.setText(categoria);
				}

			}
			return v;
		}
	}
}
